DEPTH = $(shell pwd)

include $(DEPTH)/build/Makefile.common
-include $(DEPTH)/build/Makefile.$(ARCH_OS)

SUBDIRS = src
RECURSIVE = all valid clean distclean

CFLAGS = -fPIC
CPPFLAGS := -I$(DEPTH)/proto/$(ARCH_OS)/include -I.

ifeq ("$(ARCH_OS)","i686-Linux") 
OPTIONS =
else
OPTIONS += --enable-64bit
endif

ifeq ("$(OS)","Darwin") 
LIBS = -L$(DEPTH)/proto/$(ARCH_OS)/lib -lantlr3c
else
LIBS = -Wl,-Bstatic -L$(DEPTH)/proto/$(ARCH_OS)/lib -lantlr3c -Wl,-Bdynamic
endif

main:
	cd $(DEPTH)/src/grammar && make
	cd $(DEPTH)/src/libtcl && make LIBS="$(LIBS)" install

${RECURSIVE}:
	@list='$(SUBDIRS)'; for subdir in $$list; do \
	(cd $$subdir && $(MAKE) $@) || exit 1; \
	done

test:
	${TCLSH} src/tcl/startup.tcl

setup:
	$(MKDIR) proto/$(ARCH_OS)
	cd $(DEPTH)/src/grammar && make
	cd $(DEPTH)/src/$(ANTLR_LIB) && ./configure --prefix=$(DEPTH)/proto/$(ARCH_OS) --exec-prefix=$(DEPTH)/proto/$(ARCH_OS) --enable-shared=no $(OPTIONS)
	cd $(DEPTH)/src/$(ANTLR_LIB) && make CFLAGS="$(CFLAGS)" install
	# modify antlr3config.h to remove conflicting PACKAGE_* definitions that will affect the tcl lib
	${GREP} -v PACKAGE_ $(DEPTH)/proto/$(ARCH_OS)/include/antlr3config.h > tmpfile
	${MV} tmpfile $(DEPTH)/proto/$(ARCH_OS)/include/antlr3config.h
	cd $(DEPTH)/src/libtcl && \
	CFLAGS="$(CFLAGS)" LDFLAGS="$(LIBS)"  CPPFLAGS="$(CPPFLAGS)" ./configure --prefix=$(DEPTH)/proto/$(ARCH_OS) --exec-prefix=$(DEPTH)/proto/$(ARCH_OS)

clean: mainclean

mainclean:
	$(RM) -rf proto
	$(RM) -rf $(DEPTH)/src/libtcl/generic/RIIF*
	cd $(DEPTH)/src/$(ANTLR_LIB) && make clean

distclean: clean maindistclean

maindistclean:
	cd $(DEPTH)/src/$(ANTLR_LIB) && make distclean

.PHONY: $(RECURSIVE) mainclean maindistclean
